package com.cyj.comment.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.cyj.comment.dto.LoginFormDTO;
import com.cyj.comment.dto.UserDTO;
import com.cyj.comment.entity.User;
import com.cyj.comment.mapper.UserMapper;
import com.cyj.comment.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyj.comment.utils.RegexUtil;
import com.cyj.comment.utils.Result;
import com.cyj.comment.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.cyj.comment.utils.RedisConstants.*;
import static com.cyj.comment.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chixiaowai
 * @since 2023-04-04
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1、校验手机号
        if (RegexUtil.isPhoneInvalid(phone)){
            //2、格式错误返回错误信息
            return Result.fail("手机号格式错误!");
        }
        //3、格式正确生成验证码
        String code = RandomUtil.randomNumbers(6);
        //4、将验证码存到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
//        session.setAttribute("code", code);
        //5、模拟发送验证码
        log.debug("发送验证码成功,验证码为：{}", code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginFormDTO, HttpSession session) {
        String phone = loginFormDTO.getPhone();
        //1、校验手机号
        if (RegexUtil.isPhoneInvalid(phone)){
            //2、格式错误返回错误信息
            return Result.fail("手机号格式错误");
        }
        //3、格式正确从redis中获取验证码并进行比较
//        String code = (String) session.getAttribute("code");
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        //4、验证码不一致返回错误信息
        if (cacheCode == null || !cacheCode.equals(loginFormDTO.getCode())){
            return Result.fail("验证码错误");
        }
        //5、验证码一致，根据手机号查询用户
        User user = query().eq("phone", phone).one();
        //6、用户不存在创建新用户
        if (Objects.isNull(user)){
            createUserWithPhone(phone);
        }
        //7、用户存在将用户信息保存到redis中
//        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        //7.1、生成token令牌
        String token = UUID.randomUUID().toString(true);
        //7.2、将User对象转为Hash存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //将long类型的id转为字符串
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        String tokenKey = LOGIN_USER_KEY + token;
        //7.3、存储
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        //7.4、设置token过期时间
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //获取日期
        LocalDateTime now = LocalDateTime.now();
        //拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //第几天
        int dayOfMonth = now.getDayOfMonth();
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return Result.ok();
    }

    /**
     * 创建新用户
     * @param phone
     * @return
     */
    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }


}
